package main

import (
	"context"
	"fmt"
	"github.com/cloudwego/netpoll"
	"time"
)

func main() {
	network, address := "udp", "127.0.0.1:8089"
	listener, err := netpoll.CreateListener(network, address)
	if err != nil {
		panic("create netpoll listener failed")
	}

	// event loop
	eventLoop, _ := netpoll.NewEventLoop(
		handle,
		netpoll.WithOnPrepare(prepare),
		netpoll.WithReadTimeout(time.Second),
	)

	// start
	_ = eventLoop.Serve(listener)

	// stop server ...
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_ = eventLoop.Shutdown(ctx)
}

//var a netpoll.OnPrepare = prepare
//var b netpoll.OnRequest = handle

func prepare(connection netpoll.Connection) context.Context {
	return context.Background()
}

// 有连接到后的请求处理.
func handle(ctx context.Context, connection netpoll.Connection) error {
	reader := connection.Reader()
	defer reader.Release() //
	fmt.Println("handle enter:")
	fmt.Println(reader.Len())
	msg, _ := reader.ReadString(reader.Len())
	println(msg)
	return nil
}
